import { JXDef } from "../../../conventions/JXCommon";
import { PRIORITY_VIEW } from "../../../Core/CoreDefine";
import { GCtrl } from "../../../Core/GCtrl";
import GChild from "../../../Core/GView/GChild";
import MathEx from "../../../Core/Math/MathEx";
import ShaderUtil from "../../../Shaders/Manager/ShaderUtil";
import { CMsg, CURRENCY, DETAILSBTN, GOODSTYPE, ITEM_DETAIL_FLAG, ITEM_TYPE, RPointMask, SELLSTORE } from "../../Common/Define";
import { LCoin } from "../../Common/Language";
import { VIEW_ID } from "../../Common/UI";
import { Res } from "../../Common/UIResources";
import { JXLocales } from "../../Common/Zh";
import { REquireItem } from "../../Data/RunTime/RunRaw/RItemAttach";
import RJXItem from "../../Data/RunTime/RunRaw/RJXItem";
import GameMgr from "../../Logic/GameMgr";
import JXItem from "../Common/JXItem";
const { ccclass, menu, property } = cc._decorator;

@ccclass @menu('View/Store/StoreEquipItem')
export default class StoreEquipItem extends GChild {

    @property({
        type: cc.Node,
        tooltip: "4个固定装备位置"
    })
    storeItem: cc.Node[] = [];


    @property({
        type: cc.Label,
        tooltip: "4个动态渲染文案"
    })
    storeSell: cc.Label[] = [];

    @property({
        type: cc.Sprite,
        tooltip: "4个动态渲染图片"
    })
    storeImg: cc.Sprite[] = [];

    /**购买方式索引 */
    private buyArr: any[] = [];
    /**当前对应职业装备 */
    private _curOnceEquip: SEquipDataRaw[] = null;
    /**职业商品按钮选项索引 */
    private _curEquipIndex: number = 1;
    /**货架行数 */
    private _index: number = 0;
    /**替换装备道具类型 */
    private _type: number = null;
    /**替换装备id */
    private _replaceId: Array<number> = [];

    onGLoad() {
        GCtrl.ES.on(CMsg.client.bag.onCurrencyChange, this, this.setRedPoint.bind(this), PRIORITY_VIEW)
    }

    /**
     * 先取到所有装备 
     * 在取到当前职业的装备 
     * 在取到当前职业最高等级取对应等级装备
     * 没有英雄就取初始等级的等级装备 
     * 在随机初始4个按钮 
     * 取到对应装备的交易方式 
     */

    /**
     * 
     * @param curOnceEquip 当前对应职业装备
     * @param curEquipIndex 职业商品按钮选项索引
     * @param STOREGOODS 替换货物信息(位置 种类)
     * @param index 货架行数
     */
    public init(curOnceEquip: SEquipDataRaw[], curEquipIndex: number, STOREGOODS: STOREGOODS, index: number) {
        // console.log('STOREGOODS', STOREGOODS);
        this.buyArr = [];
        this._index = index;
        // console.log('当前职业最大等级', this.heroLv);
        //宝箱说明
        let labArr = [];
        //售卖类型
        let sell: [] = GameMgr.systemConfig.value(JXDef.SYS_CONFIG_KEY.sell);
        /**使用免费次数 */
        // let isUseFree = GameMgr.userMgr.checkCanBuyFree();
        /**拷贝一份交易类型数据 */
        let sellArr = sell;
        //每个按钮每次刷新不一样的交易方式
        var count;
        //取到对应 职业类型，等级限制 ,全局品质限制的所有装备
        this._curOnceEquip = curOnceEquip;
        this._curEquipIndex = curEquipIndex;
        // console.log('this._curOnceEquip', this._curOnceEquip);
        this._replaceId = [];
        //刷新货架上每个位置的的装备信息以及交易方式
        for (let i = 0; i < this.storeItem.length; i++) {
            this.storeItem[i].getChildByName('sell').getComponent(cc.Button).interactable = true;
            ShaderUtil.normal(this.storeItem[i].getChildByName('sell'), true);
            let num = MathEx.random(0, this._curOnceEquip.length - 1);//随机一件装备
            let sellNum = MathEx.random(0, sellArr.length - 1);//随机一件装备

            /**替换英雄碎片信息值 */
            var chipInfoIndex: number = null;
            /**是否有替换 */
            let isChange: boolean = false;
            isChange = false;
            this._type = null;
            if (this._index == STOREGOODS.pillIndex[0][0]) {
                if (i == STOREGOODS.pillIndex[0][1]) {
                    this._type = GOODSTYPE.PILL;
                    isChange = true;
                }
            }
            STOREGOODS.chipIndex.forEach((v: Array<number>, s) => {
                if (v[1] == i && v[0] == this._index) {
                    this._type = GOODSTYPE.CHIP;
                    chipInfoIndex = s;
                    isChange = true;
                }
            })
            if (!isChange) {
                for (let j = 0; j < sellArr.length; j++) {
                    if (j == sellNum) {
                        count = sellArr[j];
                        // sellArr.splice(j, 1);
                    }
                }
            }


            // //是否可以使用免费次数以及交易方式原本为金币交易类型 修改为免费
            // if (!isUseFree && count == 0) {
            //     count = 1;
            // }
            // if (isUseFree && count == 1) {
            //     count = 0;
            //     isUseFree = false;
            // }

            this.assetImpl.prefab(Res.prefab.item.jxItem, (prefab: cc.Prefab) => {
                let child = this.storeItem[i].getChildByName('JXItem');
                if (child) {
                    var equipValue = null;
                    if (this._type) {
                        if (this._type == GOODSTYPE.CHIP) {
                            equipValue = [1000 + STOREGOODS.chipInfo[chipInfoIndex], ITEM_TYPE.PROP, 1];
                            this._replaceId.push(1000 + STOREGOODS.chipInfo[chipInfoIndex]);
                            let equip = new RJXItem(equipValue);
                            this.assetImpl.spriteAtlasFrame(this.storeItem[i].getComponent(cc.Sprite), Res.texture.views.common, "equip_" + 1);
                            child.getComponent(JXItem).setView(equip, ITEM_DETAIL_FLAG.NO_BG | ITEM_DETAIL_FLAG.NO_NUM | ITEM_DETAIL_FLAG.SCALEICON | ITEM_DETAIL_FLAG.STOREHERO, () => {
                            });
                            this._type = null;
                        } if (this._type == GOODSTYPE.PILL) {
                            equipValue = [200 + STOREGOODS.pillInfo, ITEM_TYPE.PROP, 1];
                            this._replaceId.push(200 + STOREGOODS.pillInfo);
                            this.storeItem[i].getChildByName('icon_201').active = true;
                            this.assetImpl.spriteAtlasFrame(this.storeItem[i].getComponent(cc.Sprite), Res.texture.views.common, "equip_" + STOREGOODS.pillInfo);
                            child.active = false;
                            // this.assetImpl.spriteAtlasFrame(this.icon, Res.texture.views.icon, 'icon_plane');
                            this._type = null;
                        }
                    } else {
                        child.active = true;
                        this._replaceId.push(null);
                        equipValue = [this._curOnceEquip[num].id, ITEM_TYPE.EQUIPDATA, 1];
                        let equip = new RJXItem(equipValue);

                        let jumpEquip: jumpEquip = {
                            insId: '',
                            bool: false,
                            site: 0
                        }

                        child.getComponent(JXItem).setView(equip, ITEM_DETAIL_FLAG.NO_BG | ITEM_DETAIL_FLAG.NO_NUM | ITEM_DETAIL_FLAG.SCALEICON | ITEM_DETAIL_FLAG.STORECHIPHIDE, () => {
                            let arr = ['0', this._curOnceEquip[num].id, 0]
                            let equip = new REquireItem(arr);
                            GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.EquipDetailsCtrl, equip, jumpEquip, null, DETAILSBTN.DETAILSBTN2);
                        });
                    }
                } else {
                    var comp = this.assetImpl.addGChild<JXItem>(prefab);
                    let equipValue = [this._curOnceEquip[num].id, ITEM_TYPE.EQUIPDATA, 1];
                    let equip = new RJXItem(equipValue);
                    comp.node.parent = this.storeItem[i];
                    comp.node.setPosition(0, 0);

                    if (this._type) {
                        if (this._type == GOODSTYPE.CHIP) {
                            equipValue = [1000 + STOREGOODS.chipInfo[chipInfoIndex], ITEM_TYPE.PROP, 1];
                            this._replaceId.push(1000 + STOREGOODS.chipInfo[chipInfoIndex]);
                            let equip = new RJXItem(equipValue);
                            this.assetImpl.spriteAtlasFrame(this.storeItem[i].getComponent(cc.Sprite), Res.texture.views.common, "equip_" + 1);
                            comp.setView(equip, ITEM_DETAIL_FLAG.NO_BG | ITEM_DETAIL_FLAG.NO_NUM | ITEM_DETAIL_FLAG.SCALEICON | ITEM_DETAIL_FLAG.STOREHERO, () => {
                            });
                            this._type = null;
                        } if (this._type == GOODSTYPE.PILL) {
                            equipValue = [200 + STOREGOODS.pillInfo, ITEM_TYPE.PROP, 1];
                            this._replaceId.push(200 + STOREGOODS.pillInfo);
                            this.storeItem[i].getChildByName('icon_201').active = true;
                            this.assetImpl.spriteAtlasFrame(this.storeItem[i].getComponent(cc.Sprite), Res.texture.views.common, "equip_" + STOREGOODS.pillInfo);
                            comp.node.active = false;
                            // this.assetImpl.spriteAtlasFrame(this.icon, Res.texture.views.icon, 'icon_plane');
                            this._type = null;
                        }
                    } else {
                        this._replaceId.push(null);
                        let jumpEquip: jumpEquip = {
                            insId: '',
                            bool: false,
                            site: 0
                        }

                        let arr = ['0', this._curOnceEquip[num].id, 0]
                        let rEquireItem = new REquireItem(arr);
                        comp.setView(equip, ITEM_DETAIL_FLAG.NO_BG | ITEM_DETAIL_FLAG.NO_NUM | ITEM_DETAIL_FLAG.SCALEICON, () => {
                            GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.EquipDetailsCtrl, rEquireItem, jumpEquip, null, DETAILSBTN.DETAILSBTN2);
                        });
                    }
                }
            })
            // this.storeItem[i].getChildByName('lab').getComponent(cc.Label).string = this._curOnceEquip[num].name;
            if (isChange) {
                this.buyArr.push(null);
            } else {
                this.storeItem[i].getChildByName('icon_201').active = false;
                let obj: equipSell = {
                    sell: count,
                    sellData: this._curOnceEquip[num]
                }
                this.buyArr.push(obj);
                this.assetImpl.spriteAtlasFrame(this.storeItem[i].getComponent(cc.Sprite), Res.texture.views.common, "equip_" + this._curOnceEquip[num].trait);
            }
            // console.log("isChange", isChange);
            labArr.push(num);
        }

        labArr.forEach((v, i) => {
            // console.log('第几个货架位置', i);

            this.initBtnLab(i, v);
        })

        // console.log('this.buyArr', this.buyArr);
        this.setRedPoint();
    }
    /**
 * @param index 第几个货架位置
 * @param num 第几件装备信息
 */
    protected initBtnLab(index: number, num: number) {
        // console.log("this.buyArr", this.buyArr[index], this._curOnceEquip[num].sellRecycle[index]);
        if (!this.buyArr[index]) {
            this.storeSell[index].node.x = 47;
            this.storeSell[index].string = '领取';//'视频' + this._curOnceEquip[num].sellRecycle[SELLSTORE.VIDEO - 1] + '';
            this.storeImg[index].spriteFrame = null;
            this.assetImpl.spriteAtlasFrame(this.storeImg[index], Res.texture.views.icon, 'icon_video');
            this.storeImg[index].node.setScale(1);
            return;
        }
        switch (this.buyArr[index].sell) {
            case SELLSTORE.COIN:
                {
                    this.storeSell[index].node.x = 47;
                    // this.storeSell[index].string = LCoin(this._curOnceEquip[num].sellRecycle[index - 1]) + '';
                    this.storeSell[index].string = LCoin(this.buyArr[index].sellData.sellRecycle[SELLSTORE.COIN - 1]);
                    this.assetImpl.spriteAtlasFrame(this.storeImg[index], Res.texture.views.icon, 'icon_101');
                    this.storeImg[index].node.setScale(0.4);
                }
                break;
            case SELLSTORE.DIAMONDS:
                {
                    this.storeSell[index].node.x = 47;
                    // this.storeSell[index].string = LCoin(this._curOnceEquip[num].sellRecycle[index - 1]) + '';
                    this.storeSell[index].string = LCoin(this.buyArr[index].sellData.sellRecycle[SELLSTORE.DIAMONDS - 1]);
                    this.assetImpl.spriteAtlasFrame(this.storeImg[index], Res.texture.views.icon, 'icon_100');
                    // console.log('DIAMONDS', index, this._curOnceEquip[num].sellRecycle[SELLSTORE.DIAMONDS - 1]);
                    this.storeImg[index].node.setScale(0.4);
                }
                break;
            case SELLSTORE.VIDEO:
                {
                    this.storeSell[index].node.x = 47;
                    this.storeSell[index].string = '领取';//'视频' + this._curOnceEquip[num].sellRecycle[SELLSTORE.VIDEO - 1] + '';
                    this.storeImg[index].spriteFrame = null;
                    this.assetImpl.spriteAtlasFrame(this.storeImg[index], Res.texture.views.icon, 'icon_video');
                    this.storeImg[index].node.setScale(1);
                }
                break;
            case SELLSTORE.FREE:
                {
                    this.storeSell[index].node.x = 33;
                    this.storeSell[index].string = '免费';
                    this.storeImg[index].spriteFrame = null;
                }
                break;
            default:
                break;
        }
    }

    protected setRedPoint() {
        // for (let i = 0; i < this.buyBtn.length; i++) {
        //     let buyInfo: DrawCurrencyInfo = this.buyBtn[i];
        //     if (buyInfo.type === STOREBUYTYPE.VIDEO) continue;
        //     let coin = new RJXItem([buyInfo.id, ITEM_TYPE.CURRENCY, buyInfo.num])
        //     let result = GameMgr.itemMgr.testCost(coin, 1, false)
        //     let target = this.boxImg[i].node.parent;
        //     GameMgr.redMgr.setRPointView(target, target, result.enough, RedpointEffect.REDPOINT);
        // }
        GameMgr.redMgr.sendValuesSettingMsgs([RPointMask.RPM_Box_Baiyin, RPointMask.RPM_Box_Huangjin, RPointMask.RPM_Box_Zhuanshu], false);
    }

    /**购买商品装备 */
    protected buyClick(CustomEventData, index: number) {
        let bool = false;
        if (!this.buyArr[index]) {
            GameMgr.sdkMgr.watchAd(() => {
                bool = true;
                if (bool) {
                    // console.log("购买商品装备");
                    this.storeItem[index].getChildByName('sell').getComponent(cc.Button).interactable = false;
                    ShaderUtil.gray(this.storeItem[index].getChildByName('sell'), true);
                    let awardArr: number[][] = [];
                    let arr = [];

                    arr.push(this._replaceId[index]);
                    arr.push(ITEM_TYPE.PROP);
                    arr.push(SELLSTORE.COIN);
                    awardArr.push(arr);
                    GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.rewardCtrl, awardArr);
                }
            })
            return;
        }
        switch (this.buyArr[index].sell) {
            case SELLSTORE.FREE: {
                bool = true;
                this.buyArr[index].sell = SELLSTORE.COIN;
                GameMgr.lUserData.useDayFree();
                this.setRedPoint();
                // GameMgr.sdkMgr.umaSetPoint(JXDef.umaPoint.storeCtrl, { msg: PointInfo.store_buy_free })
                if (bool) {
                    this.store(index);
                }
                // GameMgr.sdkMgr.umaSetPoint(JXDef.umaPoint.detailsCtrl, { msg: L(JXLocales.tower.store, this._curEquipIndex) })
                break;
            }

            case SELLSTORE.COIN: {
                let num = this.buyArr[index].sellData.sellRecycle[SELLSTORE.COIN - 1];
                let coin = new RJXItem([CURRENCY.GOLD, ITEM_TYPE.CURRENCY, num])
                let result = GameMgr.itemMgr.testCost(coin, 1, true)
                if (result.enough) {
                    GCtrl.ES.emit(CMsg.client.bag.onBagItemChange, [[CURRENCY.GOLD, ITEM_TYPE.CURRENCY, -num]])
                    bool = true;
                    // GameMgr.sdkMgr.umaSetPoint(JXDef.umaPoint.storeCtrl, { msg: PointInfo.store_buy_coin })
                    if (bool) {
                        this.store(index);
                    }
                } else {
                    GameMgr.uiMgr.showToast(result.tip)

                }
                break;
            }
            case SELLSTORE.DIAMONDS: {
                let num = this.buyArr[index].sellData.sellRecycle[SELLSTORE.DIAMONDS - 1];
                let yushi = new RJXItem([CURRENCY.YUSHI, ITEM_TYPE.CURRENCY, num]);
                let result = GameMgr.itemMgr.testCost(yushi, 1, true);
                if (result.enough) {
                    GCtrl.ES.emit(CMsg.client.bag.onBagItemChange, [[CURRENCY.YUSHI, ITEM_TYPE.CURRENCY, -num]])
                    bool = true;
                    // GameMgr.sdkMgr.umaSetPoint(JXDef.umaPoint.storeCtrl, { msg: PointInfo.store_buy_diamond })
                    if (bool) {
                        this.store(index);
                    }
                } else {
                    GameMgr.uiMgr.showToast(result.tip)
                }
                break;
            }
            case SELLSTORE.VIDEO: {
                GameMgr.sdkMgr.watchAd(() => {
                    bool = true;
                    // GameMgr.sdkMgr.umaSetPoint(JXDef.umaPoint.storeCtrl, { msg: PointInfo.store_buy_video })
                    if (bool) {
                        this.store(index);
                    }
                })
                break;
            }
            default:
                break;
        }

        let name = GameMgr.lUserData.heroType(this._curEquipIndex);
        GameMgr.sdkMgr.umaSetPoint(JXDef.umaPoint.storeCtrl, { msg: JXLocales.tower.store + '-' + name })
    }

    /**成功购买装备 */
    protected store(index: number) {
        this.storeItem[index].getChildByName('sell').getComponent(cc.Button).interactable = false;
        ShaderUtil.gray(this.storeItem[index].getChildByName('sell'), true);
        let awardArr: number[][] = [];
        let arr = [];
        arr.push(this.buyArr[index].sellData.id);
        arr.push(SELLSTORE.COIN);
        arr.push(SELLSTORE.COIN);
        awardArr.push(arr);
        GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.rewardCtrl, awardArr);
    }
}
